package demo;

import java.awt.AWTException;
import java.awt.Cursor;
import java.awt.EventQueue;
import java.awt.Robot;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.filechooser.FileFilter;
import javax.swing.JFileChooser;
import javax.swing.JMenuBar;
import javax.swing.GroupLayout;
import javax.swing.JOptionPane;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JTabbedPane;
import javax.swing.JMenuItem;
import javax.swing.JMenu;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.KeyStroke;
import java.awt.event.KeyEvent;
import java.awt.event.InputEvent;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Random;
import java.util.Vector;

import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JButton;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableModel;
import javax.swing.ImageIcon;
import javax.swing.border.LineBorder;
import java.awt.Color;
import javax.swing.JTextArea;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JComboBox;
import javax.swing.DefaultComboBoxModel;
import java.awt.Toolkit;
import javax.swing.JTextField;
import java.awt.Dimension;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import java.awt.Font;
/**
 * Hehehe
 * @author KIEN
 *
 */
public class DemoCTDL_GT extends JFrame {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private JPanel contentPane;
	private JTable table;
	private JMenuItem mntmExit;
	private JMenu mnFile;
	private JPanel panel;
	private JMenuBar menuBar;
	private JScrollPane scrollPane;
	private JButton btnAdd;
	private JPanel panel_1;
	private JMenuItem mntmOpen;
	private JButton btnLoad;
	private JButton btnGenerate;
	@SuppressWarnings("rawtypes")
	private ArrayList<Vector> data = new ArrayList<Vector>();
	private ArrayList<Vector> dataSorted = new ArrayList<Vector>();
	private final String[] FIRST_NAME = { "Bùi", "Trần", "Nguyễn", "Hồ", "Lê",
			"Hoàng", "Phan", "Phạm", "Tần", "Vũ", "Lý", "Dương", "Ngô",
			"Trương", "Văn", "Phùng" };// 16
	private final String[] MID_NAME = { "Đức", "Văn", "Thị", "Trung", "Xuân",
			"Thu", "Cẩm", "Châu", "Hồng", "Hoàng", "Hạnh", "Đình", "Đại" };// 13
	private final String[] LAST_NAME = { "Mai", "Lan", "Cúc", "Hoa", "Hương",
			"Yến", "Anh", "Oanh", "Bích", "Ngọc", "Trân", "Cương", "Cường",
			"Hùng", "Tráng", "Dũng", "Thông", "Minh", "Trí", "Tuệ", "Sáng",
			"Hoài" };// 22

	private final String DIGITS = "0123456789";
	private final String ALPHABET = "abcdefghijklmnopqrstuvwxyz";
	private JButton btnSave;
	private JMenu mnHelp;
	private JMenuItem mntmAbout;
	private JComboBox comboBox;
	private JTextArea reportTextArea;
	private JTextField txtFind;
	private JMenu mnOptions;
	private JMenuItem mntmShowData;
	private JComboBox comboBox_1;
	private JButton btnFind;
	private JMenuItem mntmSortedData;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					DemoCTDL_GT frame = new DemoCTDL_GT();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	public DemoCTDL_GT() {
		setMinimumSize(new Dimension(1102, 556));
		setIconImage(Toolkit.getDefaultToolkit().getImage(
				DemoCTDL_GT.class.getResource("/demo/images/open.png")));
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 1102, 556);
		setLocationRelativeTo(null);
		menuBar = new JMenuBar();
		setJMenuBar(menuBar);

		mnFile = new JMenu("File");
		menuBar.add(mnFile);

		mntmExit = new JMenuItem("Exit");
		mntmExit.setIcon(new ImageIcon(DemoCTDL_GT.class
				.getResource("/demo/images/exit.png")));
		mntmExit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F4,
				InputEvent.ALT_MASK));
		mntmExit.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				mntmExitActionPerformed();
			}
		});

		mntmOpen = new JMenuItem("Open ...");
		mntmOpen.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				mntmOpenActionPerformed();
			}
		});
		mntmOpen.setIcon(new ImageIcon(DemoCTDL_GT.class
				.getResource("/demo/images/open.png")));
		mntmOpen.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O,
				InputEvent.CTRL_MASK));
		mnFile.add(mntmOpen);
		mnFile.add(mntmExit);

		mnOptions = new JMenu("View");
		menuBar.add(mnOptions);

		mntmShowData = new JMenuItem("Initial data");
		mntmShowData.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				showData(data);
			}
		});
		mntmShowData.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F5, 0));
		mnOptions.add(mntmShowData);

		mntmSortedData = new JMenuItem("Sorted data");
		mntmSortedData.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				showSortedData();
			}
		});
		mntmSortedData.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F5,
				InputEvent.SHIFT_MASK));
		mnOptions.add(mntmSortedData);

		mnHelp = new JMenu("Help");
		menuBar.add(mnHelp);

		mntmAbout = new JMenuItem("About");
		mntmAbout.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				about(arg0);

			}
		});
		mntmAbout.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F1, 0));
		mnHelp.add(mntmAbout);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);

		JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);

		JLabel lblNewLabel = new JLabel("Cấu trúc dữ liệu & Giải thuật");
		lblNewLabel.setFont(new Font("Tahoma", Font.BOLD | Font.ITALIC, 20));
		lblNewLabel.setHorizontalAlignment(SwingConstants.CENTER);
		GroupLayout gl_contentPane = new GroupLayout(contentPane);
		gl_contentPane
				.setHorizontalGroup(gl_contentPane
						.createParallelGroup(Alignment.LEADING)
						.addGroup(
								Alignment.TRAILING,
								gl_contentPane
										.createSequentialGroup()
										.addContainerGap()
										.addGroup(
												gl_contentPane
														.createParallelGroup(
																Alignment.TRAILING)
														.addComponent(
																lblNewLabel,
																Alignment.LEADING,
																GroupLayout.DEFAULT_SIZE,
																1064,
																Short.MAX_VALUE)
														.addComponent(
																tabbedPane,
																Alignment.LEADING,
																GroupLayout.PREFERRED_SIZE,
																1064,
																Short.MAX_VALUE))
										.addContainerGap()));
		gl_contentPane.setVerticalGroup(gl_contentPane.createParallelGroup(
				Alignment.LEADING).addGroup(
				Alignment.TRAILING,
				gl_contentPane
						.createSequentialGroup()
						.addComponent(lblNewLabel, GroupLayout.PREFERRED_SIZE,
								37, GroupLayout.PREFERRED_SIZE)
						.addPreferredGap(ComponentPlacement.RELATED)
						.addComponent(tabbedPane, GroupLayout.DEFAULT_SIZE,
								460, Short.MAX_VALUE).addGap(3)));

		panel = new JPanel();
		tabbedPane.addTab("Bài thực hành 1 - PA 2", null, panel, null);

		scrollPane = new JScrollPane();

		JPanel panel_2 = new JPanel();
		panel_2.setBorder(new LineBorder(new Color(0, 0, 0)));

		JButton btnOk = new JButton("Đồng ý");

		btnAdd = new JButton("Th\u00EAm s\u00E1ch");
		btnAdd.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				btnAddActionPerformed();
			}
		});
		GroupLayout gl_panel_2 = new GroupLayout(panel_2);
		gl_panel_2.setHorizontalGroup(gl_panel_2.createParallelGroup(
				Alignment.TRAILING).addGroup(
				Alignment.LEADING,
				gl_panel_2.createSequentialGroup().addContainerGap()
						.addComponent(btnAdd)
						.addPreferredGap(ComponentPlacement.RELATED)
						.addComponent(btnOk)
						.addContainerGap(13, Short.MAX_VALUE)));
		gl_panel_2.setVerticalGroup(gl_panel_2.createParallelGroup(
				Alignment.LEADING)
				.addGroup(
						gl_panel_2
								.createSequentialGroup()
								.addContainerGap()
								.addGroup(
										gl_panel_2
												.createParallelGroup(
														Alignment.BASELINE)
												.addComponent(btnOk)
												.addComponent(btnAdd))
								.addContainerGap(14, Short.MAX_VALUE)));
		panel_2.setLayout(gl_panel_2);
		btnOk.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				btnOkActionPerformed();
			}
		});

		table = new JTable();
		table.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseExited(MouseEvent arg0) {
				tableMouseExited(arg0);
			}
		});
		table.setModel(new DefaultTableModel(new Object[][] {}, new String[] {
				"isbn", "author", "name", "year", "num" }) {
			/**
			 * 
			 */
			Class[] columnTypes = new Class[] { String.class, String.class,
					String.class, Integer.class, Integer.class };

			public Class getColumnClass(int columnIndex) {
				return columnTypes[columnIndex];
			}

			/*
			 * @Override public boolean isCellEditable(int row, int column) {
			 * return false; }
			 */
		});
		table.getColumnModel().getColumn(3).setPreferredWidth(73);
		scrollPane.setViewportView(table);

		JPanel panel_3 = new JPanel();
		panel_3.setBorder(new LineBorder(new Color(0, 0, 0)));

		btnLoad = new JButton("Dữ liệu từ file");
		btnLoad.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				mntmOpenActionPerformed();
			}
		});

		btnGenerate = new JButton("Sinh dữ liệu");
		btnGenerate.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				btnGenerateActionPerformed();
			}
		});

		btnSave = new JButton("Lưu dữ liệu");
		btnSave.setEnabled(false);
		btnSave.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				btnSaveActionPerformed();
			}
		});
		GroupLayout gl_panel_3 = new GroupLayout(panel_3);
		gl_panel_3.setHorizontalGroup(gl_panel_3.createParallelGroup(
				Alignment.LEADING).addGroup(
				gl_panel_3.createSequentialGroup().addContainerGap()
						.addComponent(btnLoad)
						.addPreferredGap(ComponentPlacement.UNRELATED)
						.addComponent(btnGenerate)
						.addPreferredGap(ComponentPlacement.UNRELATED)
						.addComponent(btnSave)
						.addContainerGap(25, Short.MAX_VALUE)));
		gl_panel_3
				.setVerticalGroup(gl_panel_3
						.createParallelGroup(Alignment.LEADING)
						.addGroup(
								gl_panel_3
										.createSequentialGroup()
										.addContainerGap()
										.addGroup(
												gl_panel_3
														.createParallelGroup(
																Alignment.LEADING)
														.addComponent(btnLoad)
														.addGroup(
																gl_panel_3
																		.createParallelGroup(
																				Alignment.BASELINE)
																		.addComponent(
																				btnGenerate)
																		.addComponent(
																				btnSave)))
										.addContainerGap(16, Short.MAX_VALUE)));
		panel_3.setLayout(gl_panel_3);

		JScrollPane scrollPane_1 = new JScrollPane();

		JPanel panel_4 = new JPanel();
		panel_4.setBorder(new LineBorder(new Color(0, 0, 0)));

		comboBox = new JComboBox();
		comboBox.setEnabled(false);
		comboBox.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				sort(e);
			}
		});
		comboBox.setModel(new DefaultComboBoxModel(new String[] { "Sắp xếp",
				"Interchange Sort", "Selection Sort", "Insertion Sort",
				"Binary Insertion Sort", "Bubble Sort", "Shake Sort",
				"Shell Sort", "Quick Sort" }));
		comboBox.setSelectedIndex(0);
		GroupLayout gl_panel_4 = new GroupLayout(panel_4);
		gl_panel_4.setHorizontalGroup(gl_panel_4.createParallelGroup(
				Alignment.LEADING).addGroup(
				gl_panel_4.createSequentialGroup().addContainerGap()
						.addComponent(comboBox, 0, 165, Short.MAX_VALUE)
						.addContainerGap()));
		gl_panel_4.setVerticalGroup(gl_panel_4.createParallelGroup(
				Alignment.LEADING).addGroup(
				gl_panel_4
						.createSequentialGroup()
						.addContainerGap()
						.addComponent(comboBox, GroupLayout.PREFERRED_SIZE,
								GroupLayout.DEFAULT_SIZE,
								GroupLayout.PREFERRED_SIZE)
						.addContainerGap(17, Short.MAX_VALUE)));
		panel_4.setLayout(gl_panel_4);

		reportTextArea = new JTextArea();
		reportTextArea.setEditable(false);
		scrollPane_1.setViewportView(reportTextArea);

		JPanel panel_5 = new JPanel();
		panel_5.setBorder(new LineBorder(new Color(0, 0, 0)));

		txtFind = new JTextField();
		txtFind.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				find(arg0);
			}
		});
		txtFind.setEnabled(false);
		txtFind.setColumns(10);

		btnFind = new JButton("Tìm");
		btnFind.setEnabled(false);
		btnFind.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				find(arg0);
			}
		});

		comboBox_1 = new JComboBox();
		comboBox_1.setEnabled(false);
		comboBox_1.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if (comboBox_1.getSelectedItem().toString()
						.compareTo("Tìm kiếm") != 0) {
					txtFind.setText("Tìm theo  "
							+ comboBox_1.getSelectedItem().toString());
					txtFind.setEnabled(true);
					btnFind.setEnabled(true);
				} else {
					txtFind.setText("");
					txtFind.setEnabled(false);
					btnFind.setEnabled(false);
				}
			}
		});
		comboBox_1.setModel(new DefaultComboBoxModel(new String[] { "Tìm kiếm",
				"isbn", "author", "name", "year", "number" }));
		comboBox_1.setSelectedIndex(0);
		GroupLayout gl_panel_5 = new GroupLayout(panel_5);
		gl_panel_5.setHorizontalGroup(gl_panel_5.createParallelGroup(
				Alignment.LEADING).addGroup(
				gl_panel_5
						.createSequentialGroup()
						.addContainerGap()
						.addComponent(comboBox_1, GroupLayout.PREFERRED_SIZE,
								GroupLayout.DEFAULT_SIZE,
								GroupLayout.PREFERRED_SIZE)
						.addPreferredGap(ComponentPlacement.RELATED)
						.addComponent(txtFind, GroupLayout.DEFAULT_SIZE, 99,
								Short.MAX_VALUE)
						.addGap(9)
						.addComponent(btnFind, GroupLayout.DEFAULT_SIZE, 66,
								Short.MAX_VALUE).addContainerGap()));
		gl_panel_5
				.setVerticalGroup(gl_panel_5
						.createParallelGroup(Alignment.LEADING)
						.addGroup(
								gl_panel_5
										.createSequentialGroup()
										.addContainerGap()
										.addGroup(
												gl_panel_5
														.createParallelGroup(
																Alignment.BASELINE)
														.addComponent(
																comboBox_1,
																GroupLayout.PREFERRED_SIZE,
																GroupLayout.DEFAULT_SIZE,
																GroupLayout.PREFERRED_SIZE)
														.addComponent(
																txtFind,
																GroupLayout.PREFERRED_SIZE,
																GroupLayout.DEFAULT_SIZE,
																GroupLayout.PREFERRED_SIZE)
														.addComponent(btnFind))
										.addContainerGap(
												GroupLayout.DEFAULT_SIZE,
												Short.MAX_VALUE)));
		panel_5.setLayout(gl_panel_5);
		GroupLayout gl_panel = new GroupLayout(panel);
		gl_panel.setHorizontalGroup(gl_panel
				.createParallelGroup(Alignment.TRAILING)
				.addGroup(
						gl_panel.createSequentialGroup()
								.addGroup(
										gl_panel.createParallelGroup(
												Alignment.LEADING)
												.addGroup(
														gl_panel.createSequentialGroup()
																.addGap(10)
																.addComponent(
																		panel_2,
																		GroupLayout.PREFERRED_SIZE,
																		GroupLayout.DEFAULT_SIZE,
																		GroupLayout.PREFERRED_SIZE)
																.addGap(6)
																.addComponent(
																		panel_3,
																		GroupLayout.PREFERRED_SIZE,
																		GroupLayout.DEFAULT_SIZE,
																		GroupLayout.PREFERRED_SIZE)
																.addGap(8)
																.addComponent(
																		panel_4,
																		GroupLayout.DEFAULT_SIZE,
																		168,
																		Short.MAX_VALUE)
																.addPreferredGap(
																		ComponentPlacement.RELATED)
																.addComponent(
																		panel_5,
																		GroupLayout.PREFERRED_SIZE,
																		276,
																		GroupLayout.PREFERRED_SIZE))
												.addGroup(
														gl_panel.createSequentialGroup()
																.addContainerGap()
																.addComponent(
																		scrollPane,
																		GroupLayout.DEFAULT_SIZE,
																		1037,
																		Short.MAX_VALUE))
												.addGroup(
														gl_panel.createSequentialGroup()
																.addContainerGap()
																.addComponent(
																		scrollPane_1,
																		GroupLayout.DEFAULT_SIZE,
																		1037,
																		Short.MAX_VALUE)))
								.addContainerGap()));
		gl_panel.setVerticalGroup(gl_panel.createParallelGroup(
				Alignment.TRAILING).addGroup(
				gl_panel.createSequentialGroup()
						.addContainerGap()
						.addComponent(scrollPane, GroupLayout.DEFAULT_SIZE,
								169, Short.MAX_VALUE)
						.addGap(18)
						.addGroup(
								gl_panel.createParallelGroup(Alignment.LEADING)
										.addComponent(panel_2,
												GroupLayout.PREFERRED_SIZE,
												GroupLayout.DEFAULT_SIZE,
												GroupLayout.PREFERRED_SIZE)
										.addComponent(panel_3,
												GroupLayout.PREFERRED_SIZE, 50,
												GroupLayout.PREFERRED_SIZE)
										.addComponent(panel_5,
												GroupLayout.PREFERRED_SIZE, 50,
												GroupLayout.PREFERRED_SIZE)
										.addComponent(panel_4,
												GroupLayout.PREFERRED_SIZE, 50,
												GroupLayout.PREFERRED_SIZE))
						.addGap(11)
						.addComponent(scrollPane_1, GroupLayout.PREFERRED_SIZE,
								125, GroupLayout.PREFERRED_SIZE).addGap(13)));
		panel.setLayout(gl_panel);

		panel_1 = new JPanel();
		tabbedPane.addTab("New tab", null, panel_1, null);
		GroupLayout gl_panel_1 = new GroupLayout(panel_1);
		gl_panel_1.setHorizontalGroup(gl_panel_1.createParallelGroup(
				Alignment.LEADING).addGap(0, 617, Short.MAX_VALUE));
		gl_panel_1.setVerticalGroup(gl_panel_1.createParallelGroup(
				Alignment.LEADING).addGap(0, 264, Short.MAX_VALUE));
		panel_1.setLayout(gl_panel_1);
		contentPane.setLayout(gl_contentPane);
	}

	public void btnAddActionPerformed() {
		/*
		 * table.setModel(new DefaultTableModel(new Object[][] {}, new String[]
		 * { "isbn", "author", "name", "year", "num" }) {
		 * 
		 * Class[] columnTypes = new Class[] { String.class, String.class,
		 * String.class, Integer.class, Integer.class };
		 * 
		 * public Class getColumnClass(int columnIndex) { return
		 * columnTypes[columnIndex]; }
		 * 
		 * @Override public boolean isCellEditable(int row, int column) { if
		 * (row == 0) return true; return false; } }); showData(data);
		 */
		// Thêm 1 dòng
		btnGenerate.setEnabled(false);
		Vector rowData = new Vector();
		rowData.add("");
		rowData.add("");
		rowData.add("");
		rowData.add(0);
		rowData.add(0);
		DefaultTableModel mode = (DefaultTableModel) table.getModel();
		mode.insertRow(0, rowData);
		btnAdd.setEnabled(false);
		btnLoad.setEnabled(false);
		btnSave.setEnabled(false);
		mntmOpen.setEnabled(false);
		comboBox.setSelectedIndex(0);
		comboBox_1.setSelectedIndex(0);
		comboBox.setEnabled(false);
		comboBox_1.setEnabled(false);

	}

	public void mntmExitActionPerformed() {
		System.exit(0);
	}

	public void mntmOpenActionPerformed() {
		data = new ArrayList<Vector>();
		String currentDir = System.getProperty("user.dir");
		JFileChooser fileChooser = new JFileChooser();
		fileChooser.setAcceptAllFileFilterUsed(false);// Bỏ mặng định chọn tất
														// cả các định dạng file
		fileChooser.setDialogTitle("Load file");
		fileChooser.setFileHidingEnabled(false);
		fileChooser.setCurrentDirectory(new File(currentDir));

		FileFilter fil = new FileFilter() {

			@Override
			public boolean accept(File f) {
				if (f.isDirectory()) {
					return true;
				}
				if (f.getAbsolutePath().endsWith(".dat"))
					return true;
				return false;
			}

			@Override
			public String getDescription() {
				return "Data file (*.dat)";
			}
		};
		fileChooser.setFileFilter(fil);
		int returnValue = fileChooser.showOpenDialog(this);
		if (returnValue == JFileChooser.APPROVE_OPTION) {
			deleteAllTable();
			File selectedFile = fileChooser.getSelectedFile();
			ObjectInput in = null;
			try {
				in = new ObjectInputStream(new FileInputStream(selectedFile));
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			try {
				data = (ArrayList<Vector>) in.readObject();
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			showData(data);
			btnSave.setEnabled(true);
			comboBox.setEnabled(true);
			comboBox_1.setEnabled(true);
			btnFind.setEnabled(true);
		}
	}

	public void btnGenerateActionPerformed() {
		this.setCursor(Cursor.WAIT_CURSOR);
		if (table.getRowCount() != 0)
			if (JOptionPane
					.showConfirmDialog(
							this,
							"Trên bảng hiện có dữ liệu. Chọn Yes để sinh dữ liệu mới No để làm việc với dữ liệu cũ",
							"Thông báo", JOptionPane.YES_NO_OPTION) == JOptionPane.NO_OPTION) {
				this.setCursor(Cursor.DEFAULT_CURSOR);
				return;
			}
		int size = 0;
		while (true) {
			try {
				size = Integer.valueOf(JOptionPane.showInputDialog(this,
						"Nhập vào kích thước dữ liệu", "1000"));
				break;
			} catch (NumberFormatException e) {
				int choose = JOptionPane
						.showConfirmDialog(
								this,
								"Bạn chưa nhập kích thước dữ liệu hoặc nhập sai định dạng.\nKích thước là một số nguyên\nChọn Yes để nhập lại. Chọn No để chọn kích thước mặc định là 1000.\nChọn Cancel để hủy thao tác.",
								"Thông báo", JOptionPane.YES_NO_CANCEL_OPTION);
				if (choose == JOptionPane.NO_OPTION) {
					size = 1000;
					break;
				} else if (choose == JOptionPane.CANCEL_OPTION) {
					this.setCursor(Cursor.DEFAULT_CURSOR);
					return;
				}
			}
		}
		if (size < 1) {
			JOptionPane.showMessageDialog(this, "Kích thước phải lớn hơn 0",
					"Thông báo", JOptionPane.INFORMATION_MESSAGE);
			return;
		}
		btnSave.setEnabled(true);
		comboBox.setEnabled(true);
		comboBox_1.setEnabled(true);
		comboBox.setSelectedIndex(0);
		comboBox_1.setSelectedIndex(0);
		data = new ArrayList<Vector>();
		deleteAllTable();
		Random ran = new Random();
		for (int i = 0; i < size; i++) {
			Vector row = new Vector();
			StringBuffer isbn = new StringBuffer();
			do {
				isbn = new StringBuffer();
				isbn.append(DIGITS.charAt(ran.nextInt(10)));
				isbn.append(DIGITS.charAt(ran.nextInt(10)));
				isbn.append(DIGITS.charAt(ran.nextInt(10)));
				isbn.append('-');
				isbn.append(DIGITS.charAt(ran.nextInt(10)));
				isbn.append(DIGITS.charAt(ran.nextInt(10)));
				isbn.append(DIGITS.charAt(ran.nextInt(10)));
				isbn.append('-');
				isbn.append(DIGITS.charAt(ran.nextInt(10)));
				isbn.append(DIGITS.charAt(ran.nextInt(10)));
				isbn.append(DIGITS.charAt(ran.nextInt(10)));
			} while (trungMaISBN(isbn.toString()));

			StringBuffer author = new StringBuffer();
			author.append(FIRST_NAME[ran.nextInt(16)] + " ");
			author.append(MID_NAME[ran.nextInt(13)] + " ");
			author.append(LAST_NAME[ran.nextInt(22)]);

			StringBuffer name = new StringBuffer();
			int sizeName = ran.nextInt(20);
			for (int j = 0; j < sizeName; j++) {
				name.append(ALPHABET.charAt(ran.nextInt(26)));
			}
			int year = ran.nextInt(2011 + 1 - 1900) + 1900;
			int num = ran.nextInt(100 + 1 - 1) + 1;
			row.add(isbn.toString());
			row.add(author.toString());
			row.add(name.toString());
			row.add(year);
			row.add(num);
			data.add(row);
			DefaultTableModel mode = (DefaultTableModel) table.getModel();
			mode.insertRow(0, row);
		}

		this.setCursor(Cursor.DEFAULT_CURSOR);
	}

	public void btnOkActionPerformed() {
		if (table.getRowCount() > 0) {
			btnGenerate.setEnabled(false);
			btnAdd.setEnabled(false);

			if (!checkIsbn(table.getValueAt(0, 0).toString())) {
				JOptionPane
						.showMessageDialog(
								this,
								"Bạn đã nhập sai định dạng của isbn. Định dạng đúng có dạng xxx-xxx-xxx, ví dụ 978-985-485",
								"Thông báo", JOptionPane.ERROR_MESSAGE);
			} else {
				btnSave.setEnabled(true);
				btnGenerate.setEnabled(true);
				btnAdd.setEnabled(true);
				btnLoad.setEnabled(true);
				btnSave.setEnabled(true);
				comboBox.setEnabled(true);
				comboBox_1.setEnabled(true);
				Vector rowData = new Vector();
				rowData.add(table.getValueAt(0, 0));
				rowData.add(table.getValueAt(0, 1));
				rowData.add(table.getValueAt(0, 2));
				rowData.add(table.getValueAt(0, 3));
				rowData.add(table.getValueAt(0, 4));
				data.add(0, rowData);
				/*
				 * table.setModel(new DefaultTableModel( new Object[][] {}, new
				 * String[] { "isbn", "author", "name", "year", "num" }) {
				 * Class[] columnTypes = new Class[] { String.class,
				 * String.class, String.class, Integer.class, Integer.class };
				 * 
				 * public Class getColumnClass(int columnIndex) { return
				 * columnTypes[columnIndex]; }
				 * 
				 * @Override public boolean isCellEditable(int row, int column)
				 * { return false; } });
				 */
				showData(data);

			}
		}
	}

	public void btnSaveActionPerformed() {
		ObjectOutput out = null;
		try {
			out = new ObjectOutputStream(new FileOutputStream("data.dat"));
		} catch (FileNotFoundException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		try {
			out.writeObject(data);
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

	}

	public void tableMouseExited(MouseEvent arg0) {
		// lblNewLabel.setText("Exit");
		if (arg0.getButton() != 1) {
			Robot rb = null;
			try {
				rb = new Robot();
			} catch (AWTException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			rb.keyPress(KeyEvent.VK_ENTER);
		}
	}

	public boolean checkIsbn(String isbn) {
		if (isbn.length() != 11)
			return false;
		for (int i = 0; i < isbn.length(); i++) {
			if (i != 3 && i != 7 && !Character.isDigit(isbn.charAt(i)))
				return false;
			if ((i == 3 || i == 7) && isbn.charAt(i) != '-')
				return false;
		}
		return true;
	}

	public void deleteAllTable() {
		int numRows = table.getRowCount();
		if (numRows > 0) {
			DefaultTableModel mode = (DefaultTableModel) table.getModel();
			while (mode.getRowCount() > 0) {
				mode.removeRow(0);
			}
		}
	}

	public void about(ActionEvent arg0) {
		JOptionPane.showMessageDialog(this,
				"Bùi Đức Kiên\nMã số sinh viên : 0851120036\n Lớp CN08A");
	}

	public boolean trungMaISBN(String isbn) {
		if (data.size() > 1) {
			for (Vector book : data) {
				if (book.get(0).toString().compareTo(isbn) == 0)
					return true;
			}
		}
		return false;
	}

	public void showData(ArrayList<Vector> data) {
		deleteAllTable();
		for (int i = data.size() - 1; i >= 0; i--) {
			DefaultTableModel mode = (DefaultTableModel) table.getModel();
			mode.insertRow(0, data.get(i));
		}
	}

	public void showSortedData() {
		if (dataSorted.size() == 0) {
			JOptionPane.showMessageDialog(this, "Dữ liệu chưa được sắp xếp",
					"Thông báo", JOptionPane.INFORMATION_MESSAGE);
			return;
		} else {
			showData(dataSorted);
		}
	}

	public void sort(ActionEvent e) {
		this.setCursor(Cursor.WAIT_CURSOR);
		dataSorted = new ArrayList<Vector>();
		dataSorted.addAll(data);
		int choose = comboBox.getSelectedIndex();
		switch (choose) {
		case 1:
			interchangeSort();
			break;
		case 2:
			selectionSort();
			break;
		case 3:
			insertionSort();
			break;
		case 4:
			bInsertionSort();
			break;
		case 5:
			bubbleSort();
			break;
		case 6:
			shakerSort();
			break;
		case 7:
			shellSort();
			break;
		case 8:
			quickSort();
			break;
		}
		comboBox.setSelectedIndex(0);
		this.setCursor(Cursor.DEFAULT_CURSOR);
	}

	public void interchangeSort() {

		int compared = 0, swapped = 0;
		for (int i = 0; i < dataSorted.size() - 1; i++) {
			for (int j = i + 1; j < dataSorted.size(); j++) {
				compared++;
				if (dataSorted.get(i).get(1).toString()
						.compareTo(dataSorted.get(j).get(1).toString()) > 0) {
					Collections.swap(dataSorted, i, j);
					swapped++;
				} else if (dataSorted.get(i).get(1).toString()
						.compareTo(dataSorted.get(j).get(1).toString()) == 0) {
					compared++;
					if (dataSorted.get(i).get(2).toString()
							.compareTo(dataSorted.get(j).get(2).toString()) > 0) {
						Collections.swap(dataSorted, i, j);
						swapped++;
					}
				}
			}
		}
		showData(dataSorted);
		reportTextArea.append("Interchange Sort(Đổi chỗ trực tiếp) :\n");
		reportTextArea.append("        Kích thước dữ liệu : "
				+ String.valueOf(dataSorted.size()) + "\n");
		reportTextArea.append("        Số lần so sánh : "
				+ String.valueOf(compared) + "\n");
		reportTextArea.append("        Số lần hoán vị : "
				+ String.valueOf(swapped) + "\n");
		reportTextArea
				.append("--------------------------------------------------------------------------------------------------------\n");
	}

	public void selectionSort() {

		int compared = 0, swapped = 0;
		for (int i = 0; i < dataSorted.size() - 1; i++) {
			int min = i;
			for (int j = i + 1; j < dataSorted.size(); j++) {
				compared++;
				if (dataSorted.get(min).get(1).toString()
						.compareTo(dataSorted.get(j).get(1).toString()) > 0) {
					min = j;
				} else if (dataSorted.get(min).get(1).toString()
						.compareTo(dataSorted.get(j).get(1).toString()) == 0) {
					compared++;
					if (dataSorted.get(min).get(2).toString()
							.compareTo(dataSorted.get(j).get(2).toString()) > 0) {
						min = j;
					}
				}
			}
			if (min != i) {
				Collections.swap(dataSorted, i, min);
				swapped++;
			}
		}
		showData(dataSorted);
		reportTextArea.append("Selection Sort(Chọn trực tiếp) :\n");
		reportTextArea.append("        Kích thước dữ liệu : "
				+ String.valueOf(dataSorted.size()) + "\n");
		reportTextArea.append("        Số lần so sánh : "
				+ String.valueOf(compared) + "\n");
		reportTextArea.append("        Số lần hoán vị : "
				+ String.valueOf(swapped) + "\n");
		reportTextArea
				.append("--------------------------------------------------------------------------------------------------------\n");
	}

	public void insertionSort() {
		int compared = 0, swapped = 0, i, j, tmp, k = 0, n = dataSorted.size();
		/*
		 * //Trong khi tên tác giả còn sắp xếp tăng
		 * while(dataSorted.get(k).get(1
		 * ).toString().compareTo(dataSorted.get(k+1).get(1).toString())<0) k++;
		 * 
		 * while(dataSorted.get(k).get(1).toString().compareTo(dataSorted.get(k+1
		 * ).get(1).toString())==0)
		 * if(dataSorted.get(k).get(2).toString().compareTo
		 * (dataSorted.get(k+1).get(2).toString())<0) k++;
		 */

		// Tìm vị trí k từ đó trở về đầu dãy đã sắp xếp tăng
		for (i = 0; i < n - 1; i++) {
			if (dataSorted.get(k).get(1).toString()
					.compareTo(dataSorted.get(k + 1).get(1).toString()) > 0) {
				k = i;
				break;
			}
			if (dataSorted.get(k).get(1).toString()
					.compareTo(dataSorted.get(k + 1).get(1).toString()) < 0) {
				k = i + 1;
			}
			if (dataSorted.get(k).get(1).toString()
					.compareTo(dataSorted.get(k + 1).get(1).toString()) == 0) {

				if (dataSorted.get(k).get(2).toString()
						.compareTo(dataSorted.get(k + 1).get(2).toString()) > 0) {
					k = i;
					break;
				} else
					k = i + 1;
			}
		}

		showData(dataSorted);
		reportTextArea.append("Insertion Sort(Chèn trực tiếp) :\n");
		reportTextArea.append("        Kích thước dữ liệu : "
				+ String.valueOf(dataSorted.size()) + "\n");
		reportTextArea.append("        Số lần so sánh : "
				+ String.valueOf(compared) + "\n");
		reportTextArea.append("        Số lần hoán vị : "
				+ String.valueOf(swapped) + "\n");
		reportTextArea
				.append("--------------------------------------------------------------------------------------------------------\n");
	}

	public void bInsertionSort() {
		int compared = 0, swapped = 0;
		showData(dataSorted);
		reportTextArea.append("Binary Insertion Sort(Chèn nhị phân) :\n");
		reportTextArea.append("        Kích thước dữ liệu : "
				+ String.valueOf(dataSorted.size()) + "\n");
		reportTextArea.append("        Số lần so sánh : "
				+ String.valueOf(compared) + "\n");
		reportTextArea.append("        Số lần hoán vị : "
				+ String.valueOf(swapped) + "\n");
		reportTextArea
				.append("--------------------------------------------------------------------------------------------------------\n");
	}

	public void bubbleSort() {
		int compared = 0, swapped = 0;
		showData(dataSorted);
		reportTextArea.append("Bubble Sort(Nổi bọt) :\n");
		reportTextArea.append("        Kích thước dữ liệu : "
				+ String.valueOf(dataSorted.size()) + "\n");
		reportTextArea.append("        Số lần so sánh : "
				+ String.valueOf(compared) + "\n");
		reportTextArea.append("        Số lần hoán vị : "
				+ String.valueOf(swapped) + "\n");
		reportTextArea
				.append("--------------------------------------------------------------------------------------------------------\n");
	}

	public void shakerSort() {
		int compared = 0, swapped = 0;
		showData(dataSorted);
		reportTextArea.append("Shaker Sort(Cải tiến Bubble Sort) :\n");
		reportTextArea.append("        Kích thước dữ liệu : "
				+ String.valueOf(dataSorted.size()) + "\n");
		reportTextArea.append("        Số lần so sánh : "
				+ String.valueOf(compared) + "\n");
		reportTextArea.append("        Số lần hoán vị : "
				+ String.valueOf(swapped) + "\n");
		reportTextArea
				.append("--------------------------------------------------------------------------------------------------------\n");
	}

	public void shellSort() {
		int compared = 0, swapped = 0;
		showData(dataSorted);
		reportTextArea.append("Shell Sort(Số bước giảm dần) :\n");
		reportTextArea.append("        Kích thước dữ liệu : "
				+ String.valueOf(dataSorted.size()) + "\n");
		reportTextArea.append("        Số lần so sánh : "
				+ String.valueOf(compared) + "\n");
		reportTextArea.append("        Số lần hoán vị : "
				+ String.valueOf(swapped) + "\n");
		reportTextArea
				.append("--------------------------------------------------------------------------------------------------------\n");
	}

	public void quickSort() {
		JOptionPane.showMessageDialog(this, "Quick Sort");
	}

	public void find(ActionEvent arg0) {
		int type = 0;
		if (comboBox_1.getSelectedItem().toString().compareTo("isbn") == 0) {
			type = 0;
		} else if (comboBox_1.getSelectedItem().toString().compareTo("author") == 0) {
			type = 1;
		} else if (comboBox_1.getSelectedItem().toString().compareTo("name") == 0) {
			type = 2;
		} else if (comboBox_1.getSelectedItem().toString().compareTo("year") == 0) {
			type = 3;
		} else if (comboBox_1.getSelectedItem().toString().compareTo("num") == 0) {
			type = 4;
		}
		ArrayList<Vector> dataFind = new ArrayList<Vector>();
		for (int i = 0; i < table.getRowCount(); i++) {
			if (data.get(i).get(type).toString().compareTo(txtFind.getText()) == 0) {
				dataFind.add(data.get(i));
			}
		}
		showData(dataFind);
		reportTextArea.append("Tìm kiếm : \n");
		reportTextArea.append("        Tìm theo :          "
				+ comboBox_1.getSelectedItem().toString() + "\n");
		reportTextArea.append("        Khóa tìm :          "
				+ txtFind.getText() + "\n");
		reportTextArea.append("        Số lần xuất hiện :  "
				+ String.valueOf(dataFind.size()) + "\n");
		reportTextArea
				.append("--------------------------------------------------------------------------------------------------------\n");
	}
}
